package com.yifushidai.api;

import com.yifushidai.entity.ApiUniqueMac;
import com.yifushidai.entity.KeypassBandEntity;
import com.yifushidai.mapper.ApiUniqueMacMapper;
import com.yifushidai.mapper.KeypassBandEntityMapper;
import com.yifushidai.service.KeyPassService;
import com.yifushidai.task.AsyncTask;
import com.yifushidai.utils.CustomPackUtils;
import com.yifushidai.utils.DateUtils;
import com.yifushidai.utils.ErrorCodeEnum;
import com.yifushidai.utils.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.concurrent.Future;

@RestController
@Api(tags = "静态密码")
@RequestMapping("/api/keyPass")
public class KeypassController {
    @Autowired
    private ApiUniqueMacMapper apiUniqueMacMapper;
    @Autowired
    private AsyncTask asyncTask;
    @Autowired
    private KeyPassService keyPassService;
    @Autowired
    private KeypassBandEntityMapper keyPassMapper;

    @ApiOperation(value = "查询当前密码接口", notes = "查询当前密码", produces = MediaType.APPLICATION_JSON_VALUE)
    @PostMapping("/queryKeyPass")
    public R queryKeyPass(@ApiParam(value = "联网盒mac", required = true) @RequestParam String mac) throws Exception {
        return R.ok().put(keyPassMapper.queryByMac(mac));
    }

    @ApiOperation(value = "获取临时密码接口(异步任务)", notes = "可选参数expire，格式为：yyyy-MM-dd HH:mm:ss" +
            "\n\n特别注意以下重要规则：" +
            "\n\n1. 每次手动获取临时密码取消前一次延时操作；" +
            "\n\n2. 不传expire参数或expire时间过期时，获取的临时密码为一次性，临时密码开门成功即失效；" +
            "\n\n3. 传入expire有效时间参数时，获取的临时密码有效期为expire参数所设置时间，有效时间内均可开门，超时则无法开门。")
    @PostMapping("/getTempKey")
    public R getTempKey(@ApiParam(value = "联网盒mac", required = true) @RequestParam String mac,
                        @ApiParam(value = "失效时间") @RequestParam(required = false) String expire,
                        HttpServletRequest request) throws Exception {
        ApiUniqueMac one = apiUniqueMacMapper.selectOne(ApiUniqueMac.builder().mac(mac).build());
        if (null == one) return R.error(ErrorCodeEnum.MAC_NULL);

        String temp = RandomStringUtils.randomNumeric(4);//4位 随机数
        Future<String> currentTask = asyncTask.nowPushTempKey(one, temp, request);//异步任务
        while (true) {
            if (currentTask.isDone()) {// 任务调用完成，退出循环等待
                if ("OK".equals(currentTask.get())) {
                    Date expireDate = new Date();
                    if (StringUtils.isNotBlank(expire)) {
                        long delay = DateUtils.toDate(expire).getTime() - expireDate.getTime();
                        if (delay > 0L) {
                            expireDate = DateUtils.toDate(expire);
                            asyncTask.delayPushTempKey(one, delay, request);//异步任务
                        }
                    }

                    KeypassBandEntity keypassEntity = keyPassMapper.queryByMac(one.getMac());
                    if (keypassEntity == null) {
                        return R.error(ErrorCodeEnum.DATA_NULL);
                    }
                    keypassEntity.setTempkey(temp);
                    keypassEntity.setTempstatus(CustomPackUtils.OFF_LINE);
                    keypassEntity.setUpdateTime(expireDate);
                    keyPassMapper.updateByPrimaryKeySelective(keypassEntity);
                    return R.ok().put(temp);
                } else {
                    return R.error(ErrorCodeEnum.MINA_PUSH_ERROR);
                }
            }
        }
    }

    @ApiOperation(value = "获取固定密码接口", notes = "获取固定密码", produces = MediaType.APPLICATION_JSON_VALUE)
    @PostMapping("/getFinalKey")
    public R getFinalKey(@ApiParam(value = "联网盒mac", required = true) @RequestParam String mac) throws Exception {
        return keyPassService.getFinalKey(mac);
    }

    @PostMapping("/modKey")
    @ApiOperation(value = "修改固定密码接口", notes = "修改固定密码", produces = MediaType.APPLICATION_JSON_VALUE)
    public R modFinalKey(@ApiParam(value = "联网盒mac", required = true) @RequestParam String mac,
                         @ApiParam(value = "按键密码", required = true) @RequestParam String newKey,
                         HttpServletRequest request) throws Exception {
        return keyPassService.modFinalKey(mac, newKey, request);
    }

    @ApiOperation(value = "指纹管理密码初始化接口", notes = "用户忘记指纹管理密码时，调用此接口初始化", produces = MediaType.APPLICATION_JSON_VALUE)
    @PostMapping("/initPwd")
    public R initPwd(@ApiParam(value = "联网盒mac", required = true) @RequestParam String mac,
                     @ApiParam(value = "密码类型", required = true) @RequestParam String pwdType,
                     HttpServletRequest request) throws Exception {
        return keyPassService.initPwd(mac, pwdType, request);
    }

}